//
//  OrderController.swift
//  Fancyswap
//
//  Created by Francois Gratton on 2015-03-29.
//  Copyright (c) 2015 Jonathan Muschalle. All rights reserved.
//

import UIKit

class OrderController: UITableViewController, UITextFieldDelegate, FancyViewControllerProtocol {

    var item: FancyItem?

    @IBOutlet weak var txtFirstname: UITextField!
    @IBOutlet weak var txtLastname: UITextField!
    @IBOutlet weak var txtAddress: UITextField!
    @IBOutlet weak var txtZip: UITextField!
    @IBOutlet weak var txtCity: UITextField!
    @IBOutlet weak var txtProvince: UITextField!
    @IBOutlet weak var txtCountry: UITextField!
    
    @IBOutlet weak var txtSolde: UILabel!
    @IBOutlet weak var txtItemPrice: UILabel!
    @IBOutlet weak var txtShippingCost: UILabel!
    @IBOutlet weak var txtTotalCost: UILabel!
    @IBOutlet weak var txtCalcBalance: UILabel!
    @IBOutlet weak var txtCalcBalance2: UILabel!
    
    @IBOutlet weak var btnSubmit: UIButton!
    
    let fancyApi  = FancyRestApi()
    var fieldOrder: [UITextField] = [UITextField]()
    var parentView: FancyDetailsController?
    var buttonBackColor = UIColor.blackColor()
    var lastZip: String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()

        btnSubmit.layer.cornerRadius = 10

        self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "closeKeyboard"))

        txtFirstname.delegate = self
        txtLastname.delegate = self
        txtAddress.delegate = self
        txtZip.delegate = self
        txtCity.delegate = self
        txtProvince.delegate = self
        txtCountry.delegate = self

        fieldOrder = [UITextField]()
        fieldOrder.append(txtFirstname)
        fieldOrder.append(txtLastname)
        fieldOrder.append(txtAddress)
        fieldOrder.append(txtZip)
        fieldOrder.append(txtCity)
        fieldOrder.append(txtProvince)
        fieldOrder.append(txtCountry)
        
        buttonBackColor = btnSubmit.backgroundColor!
        
        UpdateUI()
        
        // must be authenticated to continue
        if( !Authentification.IsDone() ){
            var storyboard = UIStoryboard(name: "Authentication", bundle: nil)
            var controller = storyboard.instantiateViewControllerWithIdentifier("authentication") as UINavigationController
            let custVc = controller.viewControllers[0] as AuthenticationViewController
            custVc.dismissDelegate = self
            self.presentViewController(controller, animated: true, completion: nil)
        }
        else
        {
            // fetch user's order detail after an auto login
            fancyApi.GetUserDat() {
                succeeded, msg, userData in
                if succeeded
                {
                    CurrUser = userData!
                    self.UpdateUI()
                }
                else
                {
                    fancy_token = ""
                    var storyboard = UIStoryboard(name: "Authentication", bundle: nil)
                    var controller = storyboard.instantiateViewControllerWithIdentifier("authentication") as UINavigationController
                    let custVc = controller.viewControllers[0] as AuthenticationViewController
                    custVc.dismissDelegate = self
                    self.presentViewController(controller, animated: true, completion: nil)
                }
            }
        }

    }

    ///delegate from authentication view, if authentification failed or was canceled,
    ///closes this view
    func dismissViewControllerAndTakeAction(sender:UIViewController)
    {
        self.dismissViewControllerAnimated(true, completion: nil)
        if( !Authentification.IsDone() ){
            self.parentView!.ordered = false
            self.navigationController?.popViewControllerAnimated(false)
            return
        }
        
        UpdateUI()
    }
    
    ///update textfield with values
    func UpdateUI()
    {
        txtFirstname.text = CurrUser.firstname
        txtLastname.text = CurrUser.lastname
        txtAddress.text = CurrUser.address
        lastZip = CurrUser.zip
        txtZip.text = CurrUser.zip
        txtCity.text = CurrUser.city
        txtProvince.text = CurrUser.province
        txtCountry.text = CurrUser.country
        
        zipChanged(self)
        
        txtSolde.text = "\(CurrUser.balance)"
        txtItemPrice.text = "\(item!.value)"
        txtShippingCost.text = "\(CurrUser.shipping)"
        txtTotalCost.text = "\(item!.value + CurrUser.shipping)"
        txtCalcBalance.text = "\(CurrUser.balance - (item!.value + CurrUser.shipping))"
        txtCalcBalance2.text = txtCalcBalance.text
        
        if CurrUser.balance < (item!.value + CurrUser.shipping)
        {
            txtCalcBalance.textColor = UIColor.redColor()
            txtCalcBalance2.textColor = UIColor.redColor()
            btnSubmit.enabled = false
            btnSubmit.backgroundColor = UIColor.lightGrayColor()
        }
        else
        {
            txtCalcBalance.textColor = UIColor.blackColor()
            txtCalcBalance2.textColor = UIColor.blackColor()
            btnSubmit.enabled = true
            btnSubmit.backgroundColor = UIColor(red: 0, green: 122/255, blue: 1, alpha: 1)
        }
    }
    
    ///resolve address (city, state, country) when the zip changes, overwrite values.
    @IBAction func zipChanged(sender: AnyObject) {
        if lastZip.caseInsensitiveCompare(txtZip.text) == NSComparisonResult.OrderedSame{
            //same zip
            return
        }
        lastZip = txtZip.text
        
        fancyApi.GetAddressFromZip(txtZip.text)
        {
            succeeded, msg, addr in
            if succeeded {
                self.txtCity.text = addr!.city
                self.txtProvince.text = addr!.state
                self.txtCountry.text = addr!.country
            }
        }

    }
    
    ///Commit order confirmation
    @IBAction func onClick(sender: AnyObject) {
        
        UpdateData()
        
        let alert = UIAlertController(title: "Confirmation", message: "Confirmer la commande?", preferredStyle: UIAlertControllerStyle.Alert)
        
        alert.addAction(UIAlertAction(title: "Oui", style: UIAlertActionStyle.Default, handler: {(alert: UIAlertAction!) in self.commitOrder()}))
        alert.addAction(UIAlertAction(title: "Non", style: UIAlertActionStyle.Default, handler: nil))
        
        presentViewController(alert, animated: true) { () -> Void in }
    }
    
    ///process commit, show My orders after success.
    func commitOrder()
    {
        println("ordering")
        fancyApi.CommitOrder(item!)
        {
            succeeded, msg, data in
            if succeeded {
                self.parentView!.ordered = true
                var storyboard = UIStoryboard(name: "MyOrders", bundle: nil)
                var controller = storyboard.instantiateViewControllerWithIdentifier("myOrders") as UIViewController
                self.presentViewController(controller, animated: true, completion: nil)
            }
            else {
                let alert = UIAlertController(title: "", message: "Incapable de se connecter au serveur, SVP essayez plus tard.", preferredStyle: UIAlertControllerStyle.ActionSheet)
                alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler:
                    {
                        action -> Void in
                        println("OK")
                    }
                    ))
            }
        }
    }

    ///textfield received a return, will set focus in next textfield
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        var ndx = find(fieldOrder,textField)! + 1

        if ndx >= fieldOrder.count {
            ndx = 0
        }
        
        fieldOrder[ndx].becomeFirstResponder()
        return true
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source
    override func viewWillDisappear(animated: Bool) {
        if( !Authentification.IsDone() )
        {
            return
        }
        
        UpdateData()
    }
    func UpdateData()
    {
        CurrUser.firstname = txtFirstname.text
        CurrUser.lastname = txtLastname.text
        CurrUser.address = txtAddress.text
        CurrUser.zip = txtZip.text
        CurrUser.city = txtCity.text
        CurrUser.province = txtProvince.text
        CurrUser.country = txtCountry.text
    }
    
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // Return the number of sections.
        return 2
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Return the number of rows in the section.
        if section == 0 {
            return 1
        } else {
            return 7
        }
    }
    func closeKeyboard() {
        self.view.endEditing(true)
    }

}
